<template>
  <Page name="提现" :loaing="loading">
    <div class="withdraw">
      <div class="withdraw-top" @click="showOutAccountSheet = true">
        <span>提现方式</span>
        <div class="withdraw-top-right">
          <span class="pos">{{showOutTypeName}}</span>
          <i></i>
        </div>
      </div>
      <div class="withdraw-mid">
        <div class="withdraw-mid-top" @click="showCurrencySheet = true">
          <span>提现资金币种</span>
          <div class="withdraw-mid-right">
            <span class="pos">{{showCurrencyName}}</span>
            <i></i>
          </div>
        </div>
        <form class="withdraw-form">
          <div class="withdraw-form-cont">
            <p>提现金额</p>
            <Input
              maxlength="11"
              placeholder="请输入想要提现的金额"
              filter="float"
              :disabled="isCustom"
              v-model="form.amount"
              @focus="checkCurrency"
              @blur="checkAmount" />
          </div>
        </form>

        <div class="tip-box" v-if="max_amount !== -1 && max_amount < form.amount">
          <div class="tip-alert error">
            <i class="tip-icon"></i>
            <p>余额不足，基于您的会员等级，乐钱包账户的各种币种金额和市场汇率，本次最高可提现{{max_amount}}。</p>
          </div>
        </div>
        <div class="withdraw-tips" v-else>
          <p>基于您的会员等级，乐钱包账户的各种币种金额和市场汇率，本次最高可提现{{max_amount}}{{form.currency_code}}。</p>
        </div>
      </div>
      <div class="withdraw-group">
        <div class="withdraw-group-title">
          <span>资金扣除组合</span>
          <div class="withdraw-group-title-right">
            <span class="group-title-default">{{isCustom ? '自定义' : '默认'}}</span>
            <i :class="{active: !isCustom}" @click="changeCustom">
              <span></span>
            </i>
          </div>
        </div>
        <div class="withdraw-group-cont">
          <div class="withdraw-group-cont-show" v-if="!isCustom">
            <p class="withdraw-deduct-cash"  v-if="form.amount && form.pay_group && form.pay_group.list && form.pay_group.list.length">
              <span v-for="(item,index) in form.pay_group.list" :key="index">{{index >0 ? '+' : ''}}{{item.amount}} {{item.currency_code}}</span>
            </p>
          </div>
          <div class="withdraw-group-list" v-else>
            <div
              class="withdraw-group-item"
              v-for="(item,index) in wallets"
              :key="item.code">
              <i :class="{'active':form.group[index].amount}" @click="groupItemClick(form.group[index])"></i>
              <div class="group-item-left">
                <p>{{item.name}}</p>
                <p class="group-item-tip">账户余额：{{item.amount | toFixed}}</p>
              </div>
              <div class="group-item-right">
                <Input
                  v-model="form.group[index].amount"
                  maxlength="11"
                  placeholder="请输入扣除金额"
                  filter="float"
                  :max="Number(item.amount)"
                  @blur="convertCurrency(form.group[index])"
                  :clean="false"
                  />
                <span v-show="form.group[index].amount">{{item.currency_code}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="withdraw-bottom">
        <div class="withdraw-button" >
          <button type="button"
            class="btn btn-primary btn-block"
            @click="nextStep"
            :disabled="!formvalid || lock">确认提现</button>
        </div>
      </div>

      <!-- 币种选择 -->
      <ActionSheet
        v-if="showCurrencySheet"
        title="请选择提现资金币种"
        :list="currencys"
        :value="form.currency_code"
        @close="showCurrencySheet = false"
        @select="selectCurrency"
        />

      <!-- 提现方式 -->
       <ActionSheet
        v-if="showOutAccountSheet"
        title="选择提现方式"
        :list="outAccount"
        :value="form.type"
        @close="showOutAccountSheet = false"
        @select="selectOutAccount">
          <div slot="right">
            <nuxt-link to="/setting/add-card" class="text-primary">+添加银行卡</nuxt-link>
          </div>
          <template slot-scope="{ item }" class="out-account-item">
            <div class="out-account-item">
              <i class="out-icon" :class="{'cash':!item.bank_card_no}"></i>
              <div class="tit">{{item.name}} <span v-if="item.bank_card_no">(尾号{{item.bank_card_no.substr(item.bank_card_no.length-4,4)}})</span></div>
              <i class="ic" :class="{'on':item.id === form.bank_id}"></i>
            </div>
          </template>
        </ActionSheet>
    </div>
  </Page>
</template>

<script>
import Page from "~/components/page"
import ActionSheet from "~/components/ActionSheet.vue";
import Input from "~/components/Input"

export default {
  components: {
    Page,
    ActionSheet,
    Input
  },
  async asyncData({app,store,query}){
    let list = [];
    let currencys = store.state.currencys || [];
    try{
        //获取用户钱包信息
        await store.dispatch('GET_WALLETS');
        //获取提现账户列表
        let {data:rs} = await app.$axios.post('?ct=api&ac=getout_type');
        if(rs.code == 0){
          list = rs.data.list;
        }else{
          app.$toast(rs.msg);
        }

        //获取币种
        currencys = currencys.map(item=>{
          return {
            label: item.name,
            value: item.code,
          }
        });

      }catch(e){
        app.$error(e);
      }

       //过滤钱包的空数据
      let wallets = [];
      store.state.wallets.forEach(item=>{
        if(Number(item.amount)>0){
          wallets.push(item)
        }
      })

      let form;
      if(store.state.draw.form){
        form = JSON.parse(JSON.stringify(store.state.draw.form));
      }else{
        form = {
          type:1, // 提现方式 默认选择现金
          amount:'', // 提现金额
          currency_code: query.code || 'CNY', //提现币种
          bank_id: '', //银行id，
          pay_group:{}, //默认扣费组合
          //资金组合
          group:wallets.map(item=>{
            return {
              currency:item.currency_code,
              amount:''
            }
          }),
        }
      }


    return {
      outAccount:list,
      currencys,
      wallets,
      isCustom: store.state.draw.isCustom, // 自定义扣款
      form,
      lock:store.state.draw.lock //是否已经获取接口的扣费组合
    }
  },
  data: function() {
    return {
      showCurrencySheet: false, //币种选择弹窗
      showOutAccountSheet:false, //账户选择弹窗
      max_amount: -1,
      loading:false,
      okButton: false,
      showCode: false,
    };
  },
  filters:{
    toFixed(value){
      if(isNaN(value)){
        return value;
      }else{
        let arr = String(value).split('.');
        if(arr.length > 1){
          return arr[0] + '.' + arr[1].substr(0,2);
        }else{
          return arr[0]
        }
      }
    },
  },
  computed: {
    formvalid(){
      return String(this.form.currency_code).trim()
        && ( String(this.form.amount).trim()
        || this.form.group.some(item=>String(item.amount).trim()) )
    },
    showOutTypeName(){// 根据id显示提现类型名字
      let active = this.outAccount.find(item=>item.id == this.form.bank_id)
      if(!active){
        active = this.outAccount[0];
        this.form.bank_id = active.id
        this.form.type = 1
      }else{
        this.form.type = 2
      }
      return active.name
    },
    showCurrencyName(){
      let item = this.currencys.find(item=>item.value == this.form.currency_code)
      return item.label || '请选择'
    },
  },
  async mounted(){
    //获取当前币种的最高可提现额度
    this.loading = true;
    await this.getOutData();
    this.loading = false;
  },
  methods: {
    async getOutData(){ //获取最高可提款数据
      let {data:rs} = await this.$axios.post('?ct=api&ac=getout_data',{
        currency_code:this.form.currency_code
      });
      if(rs.code == 0){
        this.max_amount = Number(rs.data.usable_amounts.amount);
      }else {
        this.$toast(rs.msg);
      }
    },
    async selectCurrency(item){ // 切换币种获取该币种的最大提现额度
      this.form.currency_code = item.value;
      this.form.amount = '';
      this.isCustom = false;
      this.form.pay_group = {};
      this.form.group.map(item=>{
        item.amount = '';
      })
      this.loading = true;
      await this.getOutData();
      this.loading = false;
    },
    changeCustom(){ // 开启/关闭自定义组合
      this.isCustom = !this.isCustom;
      this.form.amount = '';
      this.form.pay_group = {};
      this.form.group.map(item=>{
        item.amount = '';
      })
    },
    checkCurrency(e){ // 检查是否已选币种
      if(this.isCustom || !String(this.form.currency_code).trim()){
        !this.isCustom && this.$toast('请先选择转账到资金币种')
        e.target.blur();
      }
    },
    async checkAmount(e){ // 检查输入金额是否有效
      if(this.form.currency_code && this.form.amount){
        await this.getPayGroup();
        // this.amountTip = false;
        this.lock = false;

        switch(Number(this.form.pay_group.usable.state)){
          case 0: //可用
            this.lock = false;
            break;
          case 1: // 当前币种余额不够
            this.$alert({
                title:`该币种余额不足，是否使用其它币种进行兑换`,
                cancel:true,
            }).then(()=>{
              this.lock = false;
            }).catch(e=>{
              this.form.amount = '';
              this.form.pay_group={}
            })
            break;
          case 2: // 资金组合不够
            this.$alert({
                title:`该币种余额不足，使用其他币种进行兑换最高可转${this.form.pay_group.usable.amount}`,
                cancel:true,
            }).then(()=>{
              this.form.amount = this.form.pay_group.usable.amount;
              this.lock = false;
            }).catch(e=>{
              this.form.amount = '';
              this.form.pay_group={}
            })
            break;
        }
      }
    },
    async getPayGroup(){ // 获取扣款组合
      try{
        if(this.posting) return false;
        this.posting = true;
        this.lock = true;
        let { data: rs } = await this.$axios.post('?ct=api&ac=pay_group',{
          amount:this.form.amount,
          currency_code:this.form.currency_code
        });
        if(rs.code == 0){
          this.form.pay_group = rs.data;
        }else{
          this.$toast(rs.msg);
        }
      }catch(e){
        this.$toast('获取组合接口出错');
        this.$error(e);
      }
      this.posting = false;
    },

    nextStep() {
      if(!this.formvalid) return false;
      this.$store.commit("draw/setForm",JSON.parse(JSON.stringify(this.form)));
      this.$store.commit("draw/setIsCustom",this.isCustom);
      this.$store.commit("draw/setLock",this.lock);
      this.$router.push({name:'wealth-draw-confirm'});
    },
    async convertCurrency(item){
      if(item.amount == 0){
        item.amount = '';
      }
      if(this.loading) return false;
      this.loading = true;
      try {
        let {data:rs} = await this.$axios.post('?ct=api&ac=convert_currency',{
          group:this.form.group,
          to_currency:this.form.currency_code
        });
        if(rs.code == 0){
          this.form.amount = rs.data.amount != '0' ? rs.data.amount : '';
          this.lock = false;
        }else{
          this.$toast(rs.msg);
          this.lock = true;
        }
      }catch(e){
        this.$error(e);
        this.$toast('币种转换失败');
        this.lock = true;
      }
      this.loading = false;
    },
    selectOutAccount(item){ //选择提现方式
      this.form.bank_id = item.id;
      if(item.bank_card_no){ //表示银行卡提现
        this.form.type = 2;
      }else{  // 表示现金提现
        this.form.type = 1;
      }
    },
    async groupItemClick(item){ //组合资金选项点击处理
      item.amount = '';
      await this.convertCurrency();
    }
  }
};
</script>

<style lang="less" scoped>
.withdraw {
  overflow: hidden;
}
.withdraw-title {
  font-family: "PingFangSC-Medium";
  font-size: 36px;
  color: rgb(41, 41, 41);
  background-color: #fff;
}
.withdraw-title i {
  margin-left: 30px;
  margin-top: 25px;
  position: absolute;
  width: 21px;
  height: 38px;
  background: url("~assets/img/black_blue@2x.png") no-repeat;
  background-size: 21px 38px;
}
.withdraw-title p {
  line-height: 88px;
  text-align: center;
}

.withdraw-top {
  margin-top: 20px;
  height: 96px;
  background-color: #fff;
}
.withdraw-top span {
  float: left;
  margin-left: 30px;
  line-height: 96px;
  font-family: "PingFangSC-Regular";
  font-size: 32px;
}
.withdraw-top-right {
  float: right;
  margin-right: 30px;
}
.withdraw-top-right span {
  display: inline-block;
  margin-right: 12px;
  font-family: "PingFangSC-Regular";
  font-size: 30px;
}
.withdraw-top-right i {
  display: inline-block;
  margin-top: 38px;
  width: 10px;
  height: 18px;
  background: url("~assets/img/jiantou_right@2x.png") no-repeat;
  background-size: 10px 18px;
}

.withdraw-mid {
  margin-top: 20px;
  background-color: #fff;
  padding-bottom:1px;
}
.withdraw-mid-top {
  height: 96px;
  line-height: 96px;
  font-family: "PingFangSC-Regular";
  font-size: 32px;
  border-bottom: 2px solid #ededf0;
}
.withdraw-mid-top span {
  float: left;
  margin-left: 30px;
  color: rgb(41, 41, 41);
}
.withdraw-mid-right {
  float: right;
  margin-right: 30px;
}
.withdraw-mid-right span {
  display: inline-block;
  margin-right: 12px;
  font-size: 30px;
}
.withdraw-mid-right i {
  display: inline-block;
  margin-top: 38px;
  width: 10px;
  height: 18px;
  background: url("~assets/img/jiantou_right@2x.png") no-repeat;
  background-size: 10px 18px;
}

.withdraw-form {
}
.withdraw-form-cont {
  margin:0 30px;
  border-bottom: 1px solid #ededf0;
}
.withdraw-form-cont p {
  padding-top: 34px;
  font-family: "PingFangSC-Regular";
  font-size: 32px;
  color: rgb(41, 41, 41);
}

.withdraw-tips {
  margin-left: 30px;
  width: 690px;
  height: 98px;
}
.withdraw-tips p {
  line-height: 36px;
  padding-top: 16px;
  font-family: "PingFangSC-Regular";
  font-size: 24px;
  color: rgb(211, 155, 0);
}
.withdraw-tips2 {
  position: absolute;
  margin-left: 30px;
  margin-top: -128px;
}
.withdraw-tips2.active {
  display: block;
}
.withdraw-tips2-cont {
  width: 690px;
  height: 114px;
  background-color: #fff2ee;
  border-radius: 8px;
}
.withdraw-tips2-cont .corner {
  position: absolute;
  display: block;
  margin-left: 40px;
  margin-top: -28px;
  border-style: solid;
  border-width: 14px 10px 14px 10px;
  border-color: #fff #fff #fff2ee #fff;
  width: 0px;
  height: 0px;
}
.withdraw-tips2-cont .corner-tips {
  position: absolute;
  margin-left: 20px;
  margin-top: 44px;
  width: 26px;
  height: 26px;
  background: url("~assets/img/cuowufuhao@2x.png") no-repeat;
  background-size: 26px 26px;
}
.withdraw-tips2-cont p {
  position: absolute;
  margin-left: 68px;
  margin-top: 22px;
  line-height: 36px;
  font-family: "PingFangSC-Regular";
  font-size: 24px;
  color: #f05521;
}
.withdraw-group {
}
.withdraw-group-title {
  margin-top: 20px;
  height: 96px;
  line-height: 96px;
  background-color: #fff;
}
.withdraw-group-title span {
  float: left;
  margin-left: 30px;
  font-family: "PingFangSC-Regular";
  font-size: 32px;
  color: rgb(41, 41, 41);
}
.withdraw-group-title-right {
  float: right;
  margin-right: 30px;
}
.withdraw-group-title-right .group-title-default {
  margin-left: 0;
  margin-right: 10px;
  font-size: 30px;
}
.withdraw-group-title-right i {
  float: right;
  display: block;
  margin-top: 18px;
  width: 100px;
  height: 60px;
  background-color: #2086f9;
  border-radius: 60px;
}
.withdraw-group-title-right i span {
  position: absolute;
  display: block;
  margin-left: 42px;
  margin-top: 2px;
  width: 56px;
  height: 56px;
  background-color: #fff;
  border-radius: 56px;
}
.withdraw-group-title-right i.active {
  background-color: #c0c3cc;
}
.withdraw-group-title-right i.active span {
  margin-left: 2px;
}
.withdraw-group-cont {
}
.withdraw-group-cont-show {
  height: 96px;
  line-height: 96px;
  background-color: #fff;
  border-top: 2px solid #ededf0;
}
.withdraw-deduct-cash {
  margin-left: 30px;
  font-family: "SFUIDisplay-Regular";
  font-size: 30px;
  color: rgb(41, 41, 41);
}
.withdraw-group-list {
  background-color: #fff;
  border-top: 2px solid #ededf0;
}
.withdraw-group-item {
  height: 126px;
  margin-left: 30px;
  border-bottom: 2px solid #ededf0;
  display: flex;
  align-items: center;
}
.withdraw-group-item:last-child {
  border-bottom: 0;
}
.withdraw-group-item i {
  height: 40px;
  width: 40px;
  background: url("~assets/img/fuxuankuang2_unsel@2x.png") no-repeat;
  background-size: 40px 40px;
}
.withdraw-group-item i.active {
  background: url("~assets/img/fuxuankuang2_sel@2x.png") no-repeat;
  background-size: 40px 40px;
}
.group-item-left {
  color: rgb(41, 41, 41);
  line-height: 32px;
  font-size: 32px;
}
.group-item-left p {
  margin-left: 30px;
  margin-top: 28px;
}
.group-item-left .group-item-tip {
  margin-top: 16px;
  line-height: 24px;
  color: rgb(153, 153, 153);
  font-size: 24px;
}
.group-item-right {
  flex:1;
  margin-right: 30px;
  color: rgb(41, 41, 41);
  font-size: 30px;
  display: flex;
  align-items: center;
}
.group-item-right {
  /deep/ input{
     text-align: right;
   }
}
.group-item-right span {
  margin-left:20px;
}

.withdraw-bottom {
}
.withdraw-button {
  margin-top: 60px;
  margin:60px 30px;
}

.withdraw-account-tips {
  display: none;
  position: fixed;
  top: 50%;
  left: 50%;
  width: 316px;
  height: 80px;
  margin-left: -158px;
  margin-top: -40px;
  line-height: 80px;
  text-align: center;
  font-family: "PingFangSC-Regular";
  font-size: 32px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 8px;
}
.withdraw-account-tips.active {
  display: block;
}


.out-account-item {
  width: 100%;
  display: flex;
  align-items: center;
    .tit {
      flex:1;
      font-size:32px;
      color:#292929;
      .text-ellipsis();
    }
    .out-icon {
      display: block;
      margin-right:20px;
      width: 30px;
      height: 26px;
      background: url("~assets/img/brankcard@2x.png") no-repeat;
      background-size:100%!important;
      &.cash {
        background: url("~assets/img/cash@2x.png") no-repeat;
      }
    }
    .ic {
      margin-left:10px;
      display: flex;
      align-items: center;
      justify-content: center;
      width:36px;
      height:36px;
      border-radius: 50%;
      border:1px solid #c1c5cf;
      &::after {
        content:'';
        width:16px;
        height:16px;
        border-radius: 50%;
      }

      &.on {
        border-color:#2086f9;
        &::after {
          background-color:#2086f9;
        }
      }
    }
    span {
      font-size:24px;
      color:#999;
    }
}

.tip-box {
  margin:20px 30px;
}
</style>
